<?php


namespace app\api\service;

use app\api\model\ShortLink;
use think\facade\Request;

class SystemService
{
    protected static function generateCode($code_number)
    {
        $code = randString($code_number);
        $exist = ShortLink::existCode($code);
        if (!$exist) return $code;
        return self::generateCode($code_number);
    }

    public static function generateShortLink($params): array
    {
        global $globalConfig;
        $domain = Request::domain();
        if (!($globalConfig['api_generate'] ?? 0)) return [201, 'fail', '接口未启用'];
        if ($globalConfig['generate_pwd'] ?? '')
            if ($globalConfig['generate_pwd'] != ($params['pwd'] ?? ''))
                return [201, 'fail', '调用秘钥错误'];
        $exist = ShortLink::existLinkByUrl($params['url']);
        if ($exist) return [200, 'success', $domain . '/' . $exist['link_code']];
        $code = self::generateCode($globalConfig['code_number'] ?? 6);
        $result = ShortLink::generateShortLink($code, $params['url'], $globalConfig['expire_time'] ?? 999);
        if (!$result) return [201, 'fail', ''];
        return [200, 'success', $domain . '/' . $code];
    }
}